﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace 连接
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //编写数据库连接串
            string connStr = "Data Source=.;Initial Catalog=sa;User ID=sa;Password=po89090";
            //创建 SqlConnection的实例
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connStr);
                //打开数据库连接
                conn.Open();
                //判断用户名是否重复
                string checkNameSql = "select count(*) from student where idcode='{0}'";
                checkNameSql = string.Format(checkNameSql, textBox2.Text);
                //输入不能为空
                if (textBox1.Text == "" && textBox2.Text == "")
                {
                    //用户名和学号都为空为空
                    MessageBox.Show("用户名和学号不能为空！");
                    return;
                }
                else if (textBox1.Text == "")
                {
                    //用户名为空 
                    MessageBox.Show("用户名不能为空！");
                    return;
                }
                else if (textBox2.Text == "")
                {
                    //学号为空
                    MessageBox.Show("学号不能为空！");
                    return;
                }
                //创建SqlCommand对象
                SqlCommand cmdCheckName = new SqlCommand(checkNameSql, conn);
                //执行SQL语句
                int isRepeatName = (int)cmdCheckName.ExecuteScalar();
                if (isRepeatName != 0)
                {
                    //用户名重复，则不执行注册操作
                    MessageBox.Show("学号已被使用，请重新输入！");
                    return;
                }
                string sql = "insert into student(name,idcode) values('{0}','{1}')";
                //填充SQL语句
                sql = string.Format(sql, textBox1.Text, textBox2.Text);
                //创建SqlCommand对象
                SqlCommand cmd = new SqlCommand(sql, conn);
                //执行SQL语句
                int returnvalue = cmd.ExecuteNonQuery();
                //判断SQL语句是否执行成功
                if (returnvalue != -1)
                {
                    MessageBox.Show("增添学生信息成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("增添学生信息失败！" + ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    //关闭数据库连接
                    conn.Close();
                }
            }
        }
    }
}
